<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="医生名字" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属科室" prop="doctorDepartmentId">
        <el-cascader
          v-model="queryParams.doctorDepartmentId"
          :options="departmentOptions"
          placeholder="请选择所属科室"
          clearable
          @visible-change="handleDeptVisibleChange"
        >
          <template slot-scope="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="排班时间" prop="scheduleDate">
        <el-date-picker
          clearable
          v-model="queryParams.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          placeholder="请选择日期范围"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-setting" size="mini" @click="scheduling">
          {{
            schedulingStatus === "1" ? "开启智能排班" : "关闭智能排班"
          }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:schedule:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="scheduleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="排班id" align="center" prop="scheduleId" />
      <el-table-column
        label="医生id"
        align="center"
        prop="docId"
        v-if="false"
      />
      <el-table-column
        label="医生姓名"
        align="center"
        prop="doctorDO.doctorName"
      />
      <el-table-column
        label="科室"
        align="center"
        prop="departmentDO.departmentName"
      />
      <el-table-column
        label="排班日期"
        align="center"
        prop="scheduleDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scheduleDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="scheduleStartTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.scheduleStartTime }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="结束时间"
        align="center"
        prop="scheduleEndTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.scheduleEndTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排班状态" align="center" prop="scheduleStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.scheduleStatus"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
            active-text="启用"
            inactive-text="禁用"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:schedule:edit']"
            :disabled="isPastDate(scope.row.scheduleDate)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:schedule:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属科室" prop="doctorDepartmentId" v-if="isEdit">
          <el-cascader
            v-model="form.doctorDepartmentId"
            :options="departmentOptions"
            placeholder="请选择所属科室"
            clearable
            @visible-change="handleDeptVisibleChange"
            @change="handleDepartmentChange"
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="医生" prop="doctorName" v-if="isEdit">
          <el-select
            v-model="form.doctorName"
            :placeholder="
              doctorOptions.length > 0 ? '请选择医生' : '该科室没医生'
            "
            clearable
            :disabled="isDoctorDisabled"
          >
            <el-option
              v-for="doctor in doctorOptions"
              :key="doctor.id"
              :label="doctor.name"
              :value="doctor.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="scheduleDate">
          <el-date-picker
            clearable
            v-model="form.scheduleDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            :picker-options="{ disabledDate }"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="scheduleStartTime">
          <el-time-picker
            v-model="form.scheduleStartTime"
            clearable
            placeholder="请选择开始时间"
            format="HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="scheduleEndTime">
          <el-time-picker
            v-model="form.scheduleEndTime"
            clearable
            placeholder="请选择结束时间"
            format="HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentOptions } from "@/api/medicalManament/doctor";
import {
  getWorkforceList,
  updateWorkforceStatus,
  deleteWorkforce,
  updateWorkforce,
  getDoctorListByDepartment,
  addSchedule,
  toggleSchedulingStatus,
  getScheduleStatus,
} from "@/api/medicalManament/workforce";
export default {
  name: "Schedule",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      scheduleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorName: null,
        doctorDepartmentId: [],
        dateRange: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scheduleDate: [
          { required: true, message: "日期不能为空", trigger: "blur" },
        ],
        scheduleStartTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
        ],
        scheduleEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
        doctorDepartmentId: [
          { required: true, message: "所属科室不能为空", trigger: "blur" },
        ],
        doctorName: [
          { required: true, message: "医生不能为空", trigger: "blur" },
        ],
      },
      // 部门树数据
      departmentOptions: [],
      // 是不是编辑状态
      isEdit: false,
      // 医生下拉框是否禁用（默认禁用）
      isDoctorDisabled: true,
      // 医生列表数据
      doctorOptions: [],
      // 智能排班状态
      schedulingStatus: "",
    };
  },
  created() {
    this.getList();
    this.getSchedulingStatus();
  },
  methods: {
    // 智能排班开关
    scheduling() {
      const newStatus = this.schedulingStatus;
      this.$confirm(
        `是否确认${newStatus === "0" ? "关闭" : "开启"}智能排班?`,
        "确认操作",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false, // 禁止点击遮罩关闭
        }
      )
        .then(() => {
          toggleSchedulingStatus().then((res) => {
            console.log("智能开关", res);
            if (res.code !== 200) {
              this.$message.error("操作失败");
              return;
            }
            this.schedulingStatus = newStatus.toString();
            this.$message.success("操作成功");
            this.getSchedulingStatus();
          });
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    // 获取智能排班状态
    getSchedulingStatus() {
      getScheduleStatus().then((res) => {
        this.schedulingStatus = res.msg;
        console.log("智能排班开关", res);
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageNum = val;
      this.getList();
    },
    handleDepartmentChange() {
      this.isDoctorDisabled = false; // 选择科室后启用医生下拉框
      if (this.form.doctorDepartmentId.length > 0) {
        // 获取医生列表
        getDoctorListByDepartment(this.form.doctorDepartmentId[1]).then(
          (res) => {
            console.log("医生列表", res);
            this.doctorOptions = res.data.data.map((doctor) => ({
              id: doctor.doctorId,
              name: doctor.doctorName,
            }));
            // 如果医生列表为空，则禁用医生下拉框
            // if (this.doctorOptions.length === 0) {
            //   this.isDoctorDisabled = true;
            // }
          }
        );
      } else {
        this.isDoctorDisabled = true; // 如果没有选择科室，则禁用医生下拉框
        this.doctorOptions = []; // 清空医生列表
      }
    },
    // 新增或修改禁用今天之前的日期
    disabledDate(time) {
      // 今天零点的时间戳
      const today = new Date().setHours(0, 0, 0, 0);
      return time.getTime() < today;
    },
    // 判断是否为过去的日期，如果是之前的则不能进行修改
    isPastDate(date) {
      const scheduleDate = new Date(date);
      const today = new Date();
      // 只保留年月日，忽略时分秒
      scheduleDate.setHours(0, 0, 0, 0);
      today.setHours(0, 0, 0, 0);
      return scheduleDate < today;
    },

    // 格式化时间显示到组件上
    convertToDate(timeString) {
      const [hours, minutes, seconds] = timeString.split(":");
      const date = new Date();
      date.setHours(hours, minutes, seconds);
      return date;
    },
    // 格式化时间传递给后端
    formatTime(date) {
      if (!date) return null;
      const h = String(date.getHours()).padStart(2, "0");
      const m = String(date.getMinutes()).padStart(2, "0");
      const s = String(date.getSeconds()).padStart(2, "0");
      return `${h}:${m}:${s}`;
    },
    /** 获取部门树 */
    getDepartment() {
      getDepartmentOptions().then((res) => {
        console.log(res);
        this.departmentOptions = this.transformData(res.data.data);
        console.log(this.departmentOptions);
      });
    },
    transformData(data) {
      return data
        .map((item) => {
          // 仅当有子项时，才添加 children
          const children =
            item.children && item.children.length > 0
              ? item.children.map((child) => ({
                  value: child.departmentId,
                  label: child.departmentName,
                }))
              : null;
          return {
            value: item.departmentId,
            label: item.departmentName,
            children: children, // 只有有子项时才会有 children
          };
        })
        .filter((item) => item.children); // 过滤掉没有 children 的项
    },
    handleDeptVisibleChange(visible) {
      if (visible && this.departmentOptions.length === 0) {
        // 只在第一次展开时加载数据
        this.getDepartment();
      }
    },
    /** 查询排班列表 */
    getList() {
      this.loading = true;
      getWorkforceList(this.queryParams).then((res) => {
        console.log("排班数据", res);
        this.scheduleList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    // 切换状态
    handleStatusChange(row) {
      // 原始值（切换前的状态）
      const rollbackStatus = row.scheduleStatus === 0 ? 1 : 0;
      // 新值（switch 已经切换过了）
      const newStatus = row.scheduleStatus;

      this.$confirm(
        `是否确认将排班状态更新为 ${newStatus === 0 ? "启用" : "禁用"}?`,
        "确认状态修改",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false, // 禁止点击遮罩关闭
        }
      )
        .then(() => {
          // 调用后端接口更新状态
          updateWorkforceStatus(row.scheduleId).then((res) => {
            console.log("状态", res);
            if (res.data.code !== 200) {
              this.$message.error(res.data.data);
              row.scheduleStatus = rollbackStatus;
              return;
            }
            this.$message.success("状态更新成功");
          });
        })
        .catch(() => {
          // 用户点击取消，直接回滚
          row.scheduleStatus = rollbackStatus;
          this.$message.info("已取消");
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scheduleId: null,
        docId: null,
        scheduleDate: null,
        scheduleStartTime: null,
        scheduleEndTime: null,
        scheduleStatus: null,
        scheduleCreateTime: null,
        scheduleDelete: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.scheduleId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = true;
      this.open = true;
      this.title = "添加排班信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = false;
      this.form = { ...row };
      this.form.scheduleStartTime = this.convertToDate(row.scheduleStartTime); // 转换字符串为 Date
      this.form.scheduleEndTime = this.convertToDate(row.scheduleEndTime);
      this.open = true;
      this.title = "修改排班信息";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const params = {
            ...this.form,
            scheduleStartTime: this.formatTime(this.form.scheduleStartTime),
            scheduleEndTime: this.formatTime(this.form.scheduleEndTime),
            doctorId: this.form.docId,
          };
          if (this.form.scheduleId != null) {
            updateWorkforce(params).then((response) => {
              if (response.data.code !== 200) {
                this.$modal.msgError(response.data.data);
                return;
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const params = {
              ...this.form,
              scheduleStartTime: this.formatTime(this.form.scheduleStartTime),
              scheduleEndTime: this.formatTime(this.form.scheduleEndTime),
              doctorId: this.form.doctorName,
            };
            addSchedule(params).then((response) => {
              console.log(response);
              if (response.data.code !== 200) {
                this.$modal.msgError(response.data.data);
                return;
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scheduleIds = row.scheduleId || this.ids;
      this.$modal
        .confirm('是否确认删除"' + row.doctorDO.doctorName + '"的排班？')
        .then(() => {
          return deleteWorkforce(scheduleIds);
        })
        .then((res) => {
          if (res.data.code !== 200) {
            this.$modal.msgError(res.data.data);
            return;
          }
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
